package com.ymt.bpm.service.dingtalk;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;


@Service
public class DDCacheService {

    @Autowired
    CacheManager cacheManager;

    /**
     * 查询缓存
     *
     * @param key 缓存键 不可为空
     **/
    public <T extends Object> T get(String cacheName, String key) {
        if (StringUtils.isEmpty(key)) {
            return null;
        }
        Cache cache = cacheManager.getCache(cacheName);
        if (cache.get(key)!=null) {
            return (T)cache.get(key);
        }
        return null;
    }

    /**
     * 设置缓存键值  直接向缓存中插入值，这会直接覆盖掉给定键之前映射的值
     *
     * @param key 缓存键 不可为空
     * @param obj 缓存值 不可为空
     **/
    public <T extends Object> void set(String cacheName, String key, T obj) {
        Cache cache = cacheManager.getCache(cacheName);
        if (cache.get(key)!=null) {
            cache.put(key, obj);
        }
    }

    /**
     * 移除缓存
     *
     * @param key 缓存键 不可为空
     **/
    public void remove(String cacheName, String key) {
        if (StringUtils.isEmpty(key) == true) {
            return;
        }
        Cache cache = cacheManager.getCache(cacheName);
        if (cache.get(key)!=null) {
            cache.evict(key);
        }
    }

    /**
     * 是否存在缓存
     *
     * @param key 缓存键 不可为空
     **/
    public boolean contains(String cacheName, String key) {
        boolean exists = false;
        if (StringUtils.isEmpty(key) == true) {
            return exists;
        }

        Cache cache = cacheManager.getCache(cacheName);
        if (cache.get(key)!=null) {
            return true;
        }

        return exists;
    }

}
